package com.stanwind.netty.core.protocol.model;

import com.stanwind.netty.Application;
import com.stanwind.netty.constant.ServerSetting;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import java.nio.ByteBuffer;

/**
 * 请求对象
 *
 * @author westwind
 */
public class Response {

    /**
     * 时间
     */
    private int time;


    /**
     * 命令号
     */
    private short cmd;


    /**
     * 数据部分
     */
    private byte[] data;

    /**
     * 复制数组
     *
     * @param original 原数组
     * @param from     起始位置
     * @param to       结束位置
     * @return 新的数组
     */
    public static byte[] copyOfRange(byte[] original, int from, int to) {
        int newLength = to - from;
        if (newLength < 0)
            throw new IllegalArgumentException(from + " > " + to);
        byte[] copy = new byte[newLength];
        System.arraycopy(original, from, copy, 0,
                Math.min(original.length - from, newLength));
        return copy;
    }

    //TODO 修改为系统时间
    public int getTime() {
        return Application.currentTime;
    }

    public void setTime(int time) {
        this.time = time;
    }

    public short getCmd() {
        return cmd;
    }

    public void setCmd(short cmd) {
        this.cmd = cmd;
    }

    public byte[] getData() {
        return data;
    }

    public void setData(byte[] data) {
        this.data = data;
    }

    public short getLength() {
        short length = (short) (data.length + 2);
        return length;
    }

    /**
     * 得到整个包的byte
     * @return 整个包的字节集
     */
    public byte[] getAllBytes() {
        ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
        // 写包头
        buffer.writeInt(ServerSetting.FLAG);
        //写time
        buffer.writeInt(getTime());
        // length
        buffer.writeShort(getLength());
        // cmd
        buffer.writeShort(getCmd());
        // data
        if (getData() != null) {
            buffer.writeBytes(getData());
        }

        ByteBuffer bb = buffer.toByteBuffer();
        byte[] b = bb.array();
        return copyOfRange(b, 0, getLength() + 10);//长度要length前的手动设置
    }


}
